package com.springboot.core.dictionary;

import com.springboot.core.MCacheManager;
import com.springboot.sql.dao.TsysDictItemDao;
import com.springboot.sql.dao.entity.SysDictItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * On 2017/3/22 0022.
 */
@Component
public class DictionayUtils {
    private static Long defaultExp= 1000*60*60*2L;
    private static String emptyText="未知";
    private static TsysDictItemDao tsysDictItemDao;
    @Autowired
    public void setTsysDictItemDao(TsysDictItemDao tsysDictItemDao) {
        DictionayUtils.tsysDictItemDao = tsysDictItemDao;
    }
    public static DictEntry findEntry(String entry){
        DictEntry dictEntry=MCacheManager.get(entry,DictEntry.class);
        if (dictEntry==null){
            //过期加载
            return reload(entry);
        }
        return dictEntry;
    }

    public static DictItem findItem (String entry,String code){
        return findEntry(entry).getOrDefault(code,new DictItem("-1",emptyText,0));
    }

    private static DictEntry reload(String entry){
        List<SysDictItem> sysDictItemList=tsysDictItemDao.findByEntryCode(entry);
        DictEntry dictEntry =  new DictEntry();
        sysDictItemList.forEach(m->{
            DictItem dictItem = new DictItem(m.getDictItemCode(),m.getDictItemName(),m.getDictItemOrder());
            dictEntry.put(m.getDictItemCode(),dictItem);
        });
        if (dictEntry.size()>0) {
            MCacheManager.put(entry, dictEntry, defaultExp);
        }
        return dictEntry;
    }
}
